#!/usr/bin/python

# coding: utf-8

import sys
sys.path += ["../"]

import cPickle
import web
from config import DB

class cover:

    def __init__(self, where):
        self.where = where
        self.tmp = "/tmp/bj6666-sql.tmp"
        self.__connect()

    def __connect(self):
        self.db = web.database(dbn=DB.server,
                db = DB.dbname,
                user = DB.username,
                pw = DB.password
                )

    def __dump(self):
        try:
            fd = open(self.tmp, "wb")
        except IOError:
            raise
        else:
            users = self.db.select('user')
            users = [i for i in users]
            cPickle.dump(users, fd)
            print "dump %d user" % len(users)
    
    def __load(self):
        try:
            fd = open(self.tmp, 'rb')
        except IOError:
            raise
        else:
            users = cPickle.load(fd)
            return users

    def __insert(self, users):
        for i in users:
            self.db.insert('user',
                    email = i['email'],
                    password = i['password'],
                    nickname = i['nickname'],
                    location = i['location'],
                    avatar = i['avatar'],
                    tiny_avatar = i['tiny_avatar'],
                    gender = i['gender'],
                    age = i['age'],
                    regip = i['regip'],
                    regdate = i['regdate'],
                    )
        print "insert %d user" % len(users)


    def cover(self):
        if self.where == "from":
            self.__dump()
        elif self.where == "to":
            users = self.__load()
            self.__insert(users)
        else:
            sys.stderr.write("argv %s error\n" % self.where)
            exit(1)

def main():
    if len(sys.argv) < 2:
        sys.stderr.write("oops! argv error, from or to\n" )
        exit(1)

    cv = cover(sys.argv[1])
    cv.cover()

                
main()

